# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://139.199.203.70/yunwei_sys/services/wap/pay'
_QUERY_GATEWAY = 'http://139.199.203.70/yunwei_sys/services/order/orderQuery'
_QUICK_GATEWAY = 'http://139.199.203.70/yunwei_sys/services/order/quickPay'
# 创云微 witch
APP_CONF = {
    '138403779782512640': {
        'API_KEY': '82949c1841c320e254074ef3d5fc6b23',
    },
    '138403380514131968': {
        'API_KEY': '4519bb1eb56b7d69d3b6cd320d9a0600',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# 微信1003  支付宝1004
def _get_pay_type(service):
    if service == 'alipay':
        return '1004'
    else:
        return '1003'


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("cywpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    if service == 'quick':
        return create_quick_charge(pay, pay_amount, info)
    parameter_dict = OrderedDict((
        ('order_id', str(pay.id)),
        ('merchant_id', app_id),
        ('biz_code', _get_pay_type(service)),
        ('order_amt', str(int(pay_amount * 100))),
        ('return_url', '{}/pay/api/{}/cywpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('bg_url', '{}/pay/api/{}/cywpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("cywpay create  data: %s", parameter_dict)
    html = _build_form(parameter_dict, _GATEWAY)
    cache_id = redis_cache.save_html(pay.id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def create_quick_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('order_id', str(pay.id)),
        ('merchant_id', app_id),
        ('order_amt', str(int(pay_amount * 100))),
        ('return_url', '{}/pay/api/{}/cywpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('bg_url', '{}/pay/api/{}/cywpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("cywpay create  data: %s", parameter_dict)
    html = _build_form(parameter_dict, _QUICK_GATEWAY)
    cache_id = redis_cache.save_html(pay.id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# ok
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("cywpay notify data: %s", data)
    _LOGGER.info("cywpay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('cywpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['state']
    trade_no = data['up_order_id']
    total_fee = float(data['order_amt']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '0':
        _LOGGER.info('cywpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('order_id', str(pay_id)),
        ('merchant_id', app_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("cywpay query  data: %s", parameter_dict)
    headers = {'Content-type': 'application/json'}
    response = requests.post(_QUERY_GATEWAY, data=json.dumps(parameter_dict, separators=(',', ':')), headers=headers,
                             timeout=3)
    _LOGGER.info("cywpay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['state'])
        trade_no = data['up_order_id']
        total_fee = float(data['order_amt']) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 交易实际状态，0：成功，1：失败，2：处理中
        if trade_status == '0':
            _LOGGER.info('cywpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('cywpay data error, status_code: %s', response.status_code)
